#!/usr/bin/env python3
"""
测试问题视频文件
"""
import asyncio
from pathlib import Path
from app.services.video_splitter import VideoSplitter
from app.utils.logger import logger

async def test_problem_video():
    """测试问题视频文件"""
    try:
        print("🔍 测试问题视频文件...")
        
        # 问题视频文件
        problem_video = Path("uploads/24e6864f-95e0-4ae5-9406-ad9b8d66b567.mp4")
        
        if not problem_video.exists():
            print("❌ 问题视频文件不存在")
            return False
        
        print(f"📹 问题视频: {problem_video.name}")
        print(f"   文件大小: {problem_video.stat().st_size / (1024*1024):.1f}MB")
        
        # 初始化拆分器
        splitter = VideoSplitter()
        
        # 1. 获取视频信息
        print("\n1️⃣ 获取视频信息...")
        try:
            video_info = await splitter._get_video_info(problem_video)
            print(f"✅ 视频信息:")
            print(f"   时长: {video_info.get('duration', 0):.1f}秒")
            print(f"   分辨率: {video_info.get('width', 0)}x{video_info.get('height', 0)}")
            print(f"   帧率: {video_info.get('fps', 0):.1f}fps")
            print(f"   文件大小: {video_info.get('file_size', 0) / (1024*1024):.1f}MB")
        except Exception as e:
            print(f"❌ 获取视频信息失败: {e}")
            return False
        
        # 2. 测试拆分（使用与界面相同的参数）
        print("\n2️⃣ 测试视频拆分...")
        try:
            result = await splitter.split_video_by_duration(
                problem_video,
                segment_duration=60,  # 60秒一段（界面默认）
                max_segments=50,      # 50段（界面默认20，这里放宽一些）
                min_segment_duration=10  # 10秒最小时长（界面默认）
            )
            
            print(f"📊 拆分结果:")
            print(f"   需要拆分: {result.get('need_split', False)}")
            print(f"   片段数量: {len(result.get('segments', []))}")
            print(f"   总时长: {result.get('total_duration', 0):.1f}秒")
            print(f"   拆分方法: {result.get('split_method', 'unknown')}")
            
            if result.get('segments'):
                print(f"\n📋 前5个片段:")
                for i, segment in enumerate(result['segments'][:5]):
                    print(f"   片段{i+1}: {segment['filename']}")
                    print(f"     时间: {segment['start_time']:.1f}s - {segment['end_time']:.1f}s")
                    print(f"     大小: {segment['file_size'] / (1024*1024):.1f}MB")
            else:
                print("❌ 没有生成任何片段")
                
                # 检查segments目录
                segments_dir = Path("uploads/segments") / problem_video.stem
                if segments_dir.exists():
                    files = list(segments_dir.glob("*"))
                    print(f"   segments目录存在，包含 {len(files)} 个文件")
                    for file in files[:3]:
                        print(f"     {file.name}")
                else:
                    print("   segments目录不存在")
            
            return len(result.get('segments', [])) > 0
            
        except Exception as e:
            print(f"❌ 视频拆分失败: {e}")
            import traceback
            traceback.print_exc()
            return False
        
    except Exception as e:
        print(f"❌ 测试失败: {e}")
        import traceback
        traceback.print_exc()
        return False

if __name__ == "__main__":
    success = asyncio.run(test_problem_video())
    if success:
        print("\n✅ 问题视频拆分成功！")
    else:
        print("\n❌ 问题视频拆分失败！")
        print("\n💡 可能的原因:")
        print("   1. 视频文件过大")
        print("   2. 视频编码格式问题")
        print("   3. FFmpeg处理超时")
        print("   4. 磁盘空间不足")